<template>
  <div class="form-flow-entry-fragment">
    <ProcessDesigner :flow-entry-info="formFlowEntryData" @save="onSaveFlowEntry" />
  </div>
</template>

<script>
// import { mapGetters } from 'vuex'
import '@/staticDict/flowStaticDict.js'
/* eslint-disable-next-line */
import rules from '@/utils/validate.js'
/* eslint-disable-next-line */
import { DropdownWidget } from '@/utils/widget.js'
/* eslint-disable-next-line */
import { uploadMixin, statsDateRangeMixin, cachePageMixin } from '@/core/mixins'
import ProcessDesigner from '../components/ProcessDesigner.vue'
/* eslint-disable-next-line */
import { FlowEntryController, FlowEntryVariableController, FlowDictionaryController } from '@/api/flowController.js'
import {
  OnlinePageController,
  OnlineFormController,
  OnlineColumnController,
  OnlineDatasourceRelationController,
  OnlineVirtualColumnController
} from '@/api/onlineController.js'

export default {
  name: 'FormEditFlowEntry',
  components: {
    ProcessDesigner
  },
  mixins: [uploadMixin, statsDateRangeMixin, cachePageMixin],
  props: {
    flowEntry: {
      type: Object,
      default: () => {}
    }
  },
  provide() {
    return {
      flowEntry: () => this.formFlowEntryData,
      formList: () => this.defaultFormIdWidget ? this.defaultFormIdWidget.dropdownList : [],
      allVariableList: () => this.processVariableList
    }
  },
  data() {
    return {
      entryDatasource: undefined,
      formFlowEntryData: {
        entryId: undefined,
        processDefinitionName: undefined,
        processDefinitionKey: undefined,
        categoryId: undefined,
        bindFormType: this.SysFlowEntryBindFormType.ROUTER_FORM,
        pageId: undefined,
        defaultFormId: undefined,
        defaultRouterName: undefined,
        bpmnXml: undefined
      },
      documentClientHeight: this.$store.getters.clientHeight,
      categoryIdWidget: new DropdownWidget(this.loadCategoryIdDropdownList),
      pageIdWidget: new DropdownWidget(this.loadPageIdDropdownList),
      defaultFormIdWidget: new DropdownWidget(this.loadDefaultFormIdDropdownList),
      processVariableList: []
    }
  },
  computed: {
    isEdit() {
      return this.flowEntry != null || this.formFlowEntryData.entryId != null
    }
  },
  watch: {
  },
  mounted() {
    // 初始化页面数据
    this.categoryIdWidget.onVisibleChange(true)
    this.pageIdWidget.onVisibleChange(true)
    if (this.isEdit) {
      this.initFlowEntryInfo()
    }
  },
  methods: {
    onClose() {
      this.$emit('close')
    },
    // 流程绑定表单类型改变
    onBindFormTypeChange() {
      this.formFlowEntryData.pageId = undefined
      this.formFlowEntryData.defaultFormId = undefined
      this.formFlowEntryData.defaultRouterName = undefined
      this.entryDatasource = undefined
    },
    // 流程绑定表单页面改变
    onEntryPageChange() {
      this.formFlowEntryData.defaultFormId = undefined
      this.defaultFormIdWidget.dirty = true
      this.entryDatasource = null
    },
    // 获取流程分类
    loadCategoryIdDropdownList() {
      return new Promise((resolve, reject) => {
        FlowDictionaryController.dictFlowCategory({}).then(res => {
          resolve(res.getList())
        }).catch(e => {
          reject(e)
        })
      })
    },
    // 获取在线表单列表
    loadPageIdDropdownList() {
      return new Promise((resolve, reject) => {
        OnlinePageController.list({
          onlinePageDtoFilter: {
            pageType: this.SysOnlinePageType.FLOW
          }
        }).then(res => {
          resolve(res.data.dataList.filter(item => item.published))
        }).catch(e => {
          reject(e)
        })
      })
    },
    // 获取默认表单页面列表
    loadDefaultFormIdDropdownList() {
      return new Promise((resolve, reject) => {
        if (this.formFlowEntryData.pageId == null || this.formFlowEntryData.pageId === '') {
          resolve([])
          return
        }
        OnlineFormController.list({
          onlineFormDtoFilter: {
            pageId: this.formFlowEntryData.pageId
          },
          orderParam: [
            {
              fieldName: 'createTime',
              asc: true
            }
          ]
        }).then(res => {
          resolve(res.data.dataList)
        }).catch(e => {
          reject(e)
        })
      })
    },

    // 初始化流程基础信息
    initFlowEntryInfo() {
      this.formFlowEntryData = {
        processDefinitionName: undefined,
        processDefinitionKey: undefined,
        categoryId: undefined,
        bindFormType: this.SysFlowEntryBindFormType.ONLINE_FORM,
        pageId: undefined,
        defaultFormId: undefined,
        defaultRouterName: undefined,
        bpmnXml: undefined
      }
      FlowEntryController.view({
        entryId: this.flowEntry.entryId
      }).then(res => {
        this.formFlowEntryData = {
          ...this.formFlowEntryData,
          ...res.data
        }
        if (this.formFlowEntryData.bindFormType === this.SysFlowEntryBindFormType.ONLINE_FORM) {
          this.defaultFormIdWidget.onVisibleChange(true)
        }
      }).catch(e => {})
    },
    // 保存流程基础信息
    saveFlowEntryInfo(step) {
      const params = {
        flowEntryDto: {
          ...this.formFlowEntryData,
          step
        }
      }

      return this.isEdit ? FlowEntryController.update(params) : FlowEntryController.add(params)
    },
    onSaveFlowEntry(xml) {
      this.formFlowEntryData.bpmnXml = xml
      this.onSaveFlowEntryBasicInfo().then(res => {
        this.$message.success('保存成功')
      }).catch(e => {})
    },
    onSaveFlowEntryBasicInfo() {
      return this.saveFlowEntryInfo(this.SysFlowEntryStep.DATASOURCE)
    },
    // 获取流程绑定页面数据源信息
    initFlowEntryDatasourceInfo(entryId) {
      return FlowEntryController.viewDatasource({
        entryId
      })
    },
    /**
     * 获取数据模型关联信息
     */
    loadDatasourceRelation() {
      if (this.entryDatasource == null) return Promise.resolve()
      return OnlineDatasourceRelationController.list({
        onlineDatasourceRelationDtoFilter: {
          datasourceId: this.entryDatasource.datasourceId
        }
      })
    },
    // 获取在线表单数据表字段列表
    loadOnlineTableColumns(tableId, owner) {
      if (tableId == null || tableId === '') return Promise.reject()

      return new Promise((resolve, reject) => {
        const params = {
          onlineColumnDtoFilter: {
            tableId
          }
        }

        OnlineColumnController.list(params).then(res => {
          owner.columnList = res.data.dataList
          resolve()
        }).catch(e => {
          reject(e)
        })
      })
    },
    /**
     * 获取数据源下所有表字段
     */
    loadDatasourceAllColumnList() {
      if (this.entryDatasource == null) return Promise.resolve()
      const allHttpCalls = [
        this.loadOnlineTableColumns(this.entryDatasource.masterTableId, this.entryDatasource)
      ]
      this.entryDatasource.relationList.forEach(relation => {
        if (relation.relationType === this.SysOnlineRelationType.ONE_TO_ONE) {
          allHttpCalls.push(this.loadOnlineTableColumns(relation.slaveTableId, relation))
        }
      })

      return Promise.all(allHttpCalls)
    },
    // 获取流程绑定页面数据源信息
    initFlowDatasourceInfo() {
      return new Promise((resolve, reject) => {
        if (this.entryDatasource != null) return resolve()
        if (this.formFlowEntryData.bindFormType === this.SysFlowEntryBindFormType.ONLINE_FORM) {
          OnlinePageController.listOnlinePageDatasource({
            pageId: this.formFlowEntryData.pageId
          }).then(res => {
            this.entryDatasource = res.data.dataList[0]
            return this.loadDatasourceRelation()
          }).then(res => {
            this.entryDatasource.relationList = res.data.dataList || []
            return this.loadDatasourceAllColumnList()
          }).then(res => {
            return OnlineVirtualColumnController.list({
              onlineVirtualColumnDtoFilter: {
                datasourceId: this.entryDatasource.datasourceId
              }
            })
          }).then(res => {
            const virtualColumnList = res.data.dataList
            if (Array.isArray(virtualColumnList)) {
              if (!Array.isArray(this.entryDatasource.columnList)) this.entryDatasource.columnList = []
              this.entryDatasource.columnList.push(...virtualColumnList.map(item => {
                return {
                  ...item,
                  columnId: item.virtualColumnId,
                  columnName: item.objectFieldName,
                  columnComment: item.columnPrompt
                }
              }))
            }
            resolve()
          }).catch(e => {
            reject(e)
          })
        } else {
          this.entryDatasource = null
          resolve()
        }
      })
    }
  }
}
</script>

<style  lang="scss">
  .form-flow-entry-fragment {
    display: flex;
    flex-direction: column;
    margin: 10px 10px 20px 10px;
    .blueLink {
      color: #409eff;
      font-size: 14px;
      margin-left: 20px;
      cursor: pointer;
    }
    .btnList {
      margin-top:20px;
      display: flex;
      justify-content: right;
      float: right;
      .submitBtn {
        margin-right: 30px;
      }
    }
    .fromFlex {
      height: 36px;
      display: flex;
      align-items: center;
    }
    .base-info {
      display: flex;
      margin-bottom: 20px;
      .basics-info {
        width: 100%;
      }
    }
  }
</style>
